package com.yx.shop.web.controller;

import com.alibaba.druid.util.StringUtils;
import com.yx.shop.common.Const;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Classname ${NAME}
 * @Description TODO:父类方法,优化子类方法冗余
 * @Date 2021/05/06 10:05
 * @Created by yx
 */
@WebServlet(name = "BaseServlet")
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1获取标识符参数
            System.out.println("==========baseServlet开始==========");
            // 2判断是否为null
            String method = request.getParameter("method");
            if (StringUtils.isEmpty(method)) {
                //设置默认值
                method = "index";
            }
            //3获取类对象
            Class<? extends BaseServlet> aClass = this.getClass();
            System.out.println("this====>" + this);
            //4通过类对象和标识符获取方法
            Method classMethod = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //5通过方法对象调用方法
//            Object invoke = classMethod.invoke(this, request, response);
            String result = (String) classMethod.invoke(this, request, response);

            //只处理转发,重定向,响应json数据等操作,不包含二进制文件,例如验证码.
            if (result!=null){
                if (result.contains(Const.FORWORD)){
                    request.getRequestDispatcher(result.substring(result.indexOf(":")+1)).forward(request,response);
                }else if (result.contains(Const.REDIRECT)){
                    response.sendRedirect(result.substring(result.indexOf(":")+1));
                }else {
                    //不是转发与重定向,判定为json数据,响应给客户端
                    response.getWriter().print(result);
                }
            }

            System.out.println("==========baseServlet结束==========");
        } catch (Exception e) {
            e.printStackTrace();
            //如果出现没有填写的路径标识符 如 method=xxxx ,跳到index首页
            index(request,response);
        }
    }


    /**
     * @Author:yx
     * @return void
     * @Date 2021/05/06 11:42
     * @param request
     * @param response
     * @Description:默认的首页,放在父类,方便各个不同的子类均可使用
     **/
    public void index(HttpServletRequest request,HttpServletResponse response) throws IOException {
        System.out.println(this);
        System.out.println("首页index");
//        response.getWriter().print("xxx");
        response.sendRedirect("/index.jsp");
    }


}
